package nio.bytebuffer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Order {

    public static void main(String[] args) {

        orderNotConsistent();

    }

    private static void orderNotConsistent() {

        ByteBuffer byteBuffer1 = ByteBuffer.allocate(8);
        byteBuffer1.order(ByteOrder.BIG_ENDIAN);
        byteBuffer1.putInt(123);
        byteBuffer1.putInt(567);

        byteBuffer1.flip();

        System.out.println(byteBuffer1.getInt());
        System.out.println(byteBuffer1.getInt());

        ByteBuffer byteBuffer2 = ByteBuffer.wrap(byteBuffer1.array());
        /**
         * byteBuffer1 的 order 是 BIG_ENDIAN，用 byteBuffer1.array() 创建的 byteBuffer2，
         * 如果 order 设置成 LITTLE_ENDIAN，将无法正确的读取到数据；
         */
        byteBuffer2.order(ByteOrder.LITTLE_ENDIAN);
        System.out.println(byteBuffer2.getInt()); // 2063597568
        System.out.println(byteBuffer2.getInt()); // 922877952

    }

    private static void orderDemo() {

        int value = 123456789;
        ByteBuffer bytebuffer1 = ByteBuffer.allocate(4);

        System.out.print(bytebuffer1.order() + " "); // BIG_ENDIAN
        System.out.print(bytebuffer1.order() + " "); // BIG_ENDIAN

        bytebuffer1.putInt(value);

        byte[] byteArray = bytebuffer1.array();
        for (int i = 0; i < byteArray.length; i++) {
            System.out.print(byteArray[i] + " ");
        }

        System.out.println();

        bytebuffer1 = ByteBuffer.allocate(4);
        System.out.print(bytebuffer1.order() + " ");
        bytebuffer1.order(ByteOrder.BIG_ENDIAN);
        System.out.print(bytebuffer1.order() + " ");

        bytebuffer1.putInt(value);
        byteArray = bytebuffer1.array();
        for (int i = 0; i < byteArray.length; i++) {
            System.out.print(byteArray[i] + " ");
        }

        System.out.println();

        bytebuffer1 = ByteBuffer.allocate(4);
        System.out.print(bytebuffer1.order() + " ");
        bytebuffer1.order(ByteOrder.LITTLE_ENDIAN); // 改变了 ByteBuffer 的存放顺序
        System.out.print(bytebuffer1.order() + " ");

        bytebuffer1.putInt(value);
        byteArray = bytebuffer1.array();
        for (int i = 0; i < byteArray.length; i++) {
            System.out.print(byteArray[i] + " ");
        }

    }

}
